﻿using Microsoft.EntityFrameworkCore;
using YDT_OrderService.Domains.Entities;

namespace YDT_OrderService.Infrastructure.Data
{
    public class OrderServiceDbContext : DbContext
    {
        public OrderServiceDbContext(DbContextOptions<OrderServiceDbContext> options) : base(options) { }

        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderItem> OrderItems { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Order>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.OrderType).IsRequired().HasMaxLength(50);
                entity.Property(e => e.OrderSn).IsRequired().HasMaxLength(50);
                entity.Property(e => e.OrderTotalPrice).HasColumnType("decimal(18,2)");
                entity.Property(e => e.OrderName).IsRequired().HasMaxLength(100);
                entity.Property(e => e.OrderTel).IsRequired().HasMaxLength(20);
                entity.Property(e => e.OrderAddress).IsRequired().HasMaxLength(500);
                entity.Property(e => e.OrderRemark).HasMaxLength(1000);

                entity.HasMany(e => e.OrderItems)
                      .WithOne()
                      .HasForeignKey("OrderId")
                      .OnDelete(DeleteBehavior.Cascade);

                entity.HasIndex(e => e.OrderSn).IsUnique();
                entity.HasIndex(e => e.UserId);
            });

            modelBuilder.Entity<OrderItem>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.OrderSn).IsRequired().HasMaxLength(50);
                entity.Property(e => e.ProductName).IsRequired().HasMaxLength(200);
                entity.Property(e => e.ProductUrl).HasMaxLength(500);
                entity.Property(e => e.ItemPrice).HasColumnType("decimal(18,2)");
                entity.Property(e => e.ItemTotalPrice).HasColumnType("decimal(18,2)");

                entity.HasIndex(e => e.OrderSn);
                entity.HasIndex(e => e.ProductId);
            });

            // 配置枚举转换
            modelBuilder.Entity<Order>()
                .Property(e => e.OrderStatus)
                .HasConversion<string>();
        }
    }
}
